package com.yubest.security.config;

import com.yubest.security.filter.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
// 启用方法级别的权限认证
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    
    @Value("${ignoreUris}")
    private String[] ignoreUris;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(ignoreUris).permitAll()
                .anyRequest().authenticated();

        http.formLogin();

        // 退出
        http.logout()
                .logoutUrl("/logout")
                // 登出前调用，可用于日志
                .addLogoutHandler(new MyLogoutHandler());

        http.exceptionHandling()
                // 已登入用户的权限错误
                .accessDeniedHandler(new MyAccessDeniedHandler())
                // 未登入用户的权限错误
                .authenticationEntryPoint(new MyAuthenticationEntryPoint());

        // 禁用 csrf
        http.csrf().disable();

        // 禁用 session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // 登陆校验，替换原先的表单登入 Filter
        http.addFilterAt(new LoginFilter(super.authenticationManager()), UsernamePasswordAuthenticationFilter.class);

        // 权限码校验
        http.addFilter(new VerifyFilter(super.authenticationManager()));

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

}
